#!/bin/bash 

:'
Copyright (c) 2022 Aogo技术栈
   Btznb宝塔智能备 is licensed under Mulan PSL v2.
   You can use this software according to the terms and conditions of the Mulan PSL v2. 
   You may obtain a copy of Mulan PSL v2 at:
               http://license.coscl.org.cn/MulanPSL2 
   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.  
   See the Mulan PSL v2 for more details. 
   '

# 判断是否拥有ROOT权限
if [ $(whoami) != "root" ];then
	echo "请使用root权限执行该脚本文件！"
	exit 1;
fi

# 接收并判断传入参数
while getopts y:d: OPT; do
 case ${OPT} in
  y) domain=${OPTARG}
    ;;
  d) dbname=${OPTARG}
    ;;
  ?)
    printf "[使用规则] `date '+%F %T'` -y <YOUR_DOMAIN> -d <YOUR_DBNAME>\n" >&2
    exit 1;
 esac
done

# 判断是否传入必须参数
if [ -z "${domain}" -o -z "${dbname}" ]; then
  echo "请务必传入站点主域名及数据库名！"
  exit 1;
fi

domi=${domain}
dbname=${dbname}

apt install -y unzip zip
yum install -y zip unzip

function echo_green
{
        echo -e "\033[32m$1\033[0m"
}
 
echo_green "欢迎使用小白-宝塔面板单站点备份工具!"
 
rm -f /beifen.zip
rm -rf /beifen
rm -rf /$domi

mkdir /beifen
mkdir /beifen/nginx
mkdir /beifen/ssl
mkdir /beifen/weijingtai
cd /www/wwwroot/$domi
zip -r /beifen/www.zip ./*
cd
cp /www/server/panel/vhost/nginx/$domi.conf /beifen/nginx/$domi.conf
cp /www/server/panel/vhost/rewrite/$domi.conf /beifen/weijingtai/$domi.conf
zip -r /beifen/ssl/$domi.zip /www/server/panel/vhost/cert/$domi
sed -i 's/\[mysqld\]/\[mysqld\]\nskip-grant-tables/g' /etc/my.cnf
service mysql restart
mysqldump -hlocalhost -uroot -p123456 -d $dbname >/beifen/beifen.sql
    
cd /beifen
mkdir /$domi
chmod 755 ./
zip -r /$domi/beifen.zip ./*
cd /
rm -rf /beifen

sed -i '/skip-grant-tables/d' /etc/my.cnf
service mysql restart

echo "=================================================================="
echo  "已结束，如有错误请联系QQ：3122683591"
echo -e "您已完成此站点的备份，压缩包为 /你的站点主域名/beifen.zip 文件(根目录为/），其中www.zip为网站文件，beifen.sql为站点对应数据库sql文件，nginx目录内为站点nginx配置文件，ssl目录内为ssl配置文件，weijingtai目录内为伪静态配置文件，文件内即为站点nginx伪静态规则。"
echo -e "=================================================================="
echo "如果不会备份恢复，可参考:"
echo_green "https://www.aogo.cc/?p=118"
